﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using TrainingsApp.Logic.Import.Model;


namespace TrainingsApp.Logic.Import.Template {
    public class XLS_SchoolDataReader_1 : ITemplateReader {
        public Dictionary<int, object> ReadAll(int keyId, string location, int templateType) {
            Dictionary<int, object> dict = new Dictionary<int, object>(5);
            HSSFWorkbook hssfworkbook = null;
            using (FileStream file = new FileStream(location, FileMode.Open, FileAccess.Read)) {
                hssfworkbook = new HSSFWorkbook(file);
            }

            List<SchoolTemplate_1> sheetContent = null;
            ISheet sheet = null;
            System.Collections.IEnumerator rows = null;
            for (int i = 0; i < 4; i++) {
                sheet = hssfworkbook.GetSheetAt(i);
                rows = sheet.GetRowEnumerator();
                int j = 0;
                sheetContent = new List<SchoolTemplate_1>(sheet.LastRowNum);
                while (rows.MoveNext()) {
                    IRow row = (HSSFRow)rows.Current;
                    if (j == 0) { j++; continue; }

                    var cell1 = row.GetCell(0);
                    var cell2 = row.GetCell(1);
                    if (cell2 == null) {
                        j++;
                        continue;
                    }
                    var cell3 = row.GetCell(2);
                    var cell4 = row.GetCell(3);
                    var cell5 = row.GetCell(4);
                    var cell6 = row.GetCell(5);
                    var cell7 = row.GetCell(6);
                    var cell8 = row.GetCell(7);
                    sheetContent.Add(new SchoolTemplate_1 {
                        Address = GetString(cell8),
                        AreaName = GetString(cell1),
                        ProvinceName = "浙江省",
                        RegionName = GetString(cell2),
                        SchoolCode = GetString(cell4),
                        SchoolName = GetString(cell5),
                        SchoolType = GetString(cell6),
                        TownName = GetString(cell3),
                        ZipCode = GetString(cell7)
                    });

                    j++;
                }

                dict.Add(i, sheetContent);
            }
            return dict;
        }

        private void Debug(ICell cell) {
            if (cell == null) {
                Console.WriteLine("");
            }
            else {
                Console.WriteLine(String.Format("{0}:{1}", cell.ColumnIndex, GetString(cell)));
            }

        }

        private string GetString(ICell cell) {
            if (cell == null) return string.Empty;
            else return cell.ToString();
        }
    }
}
